package com.creatshare.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

//@WebFilter("/*")
public class UserLoginFilter implements Filter {

	@Override
	public void destroy() {
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain filterChain)
			throws IOException, ServletException {
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) resp;
		HttpSession session = request.getSession();
		if (request.getServletPath().endsWith("login") && request.getMethod().toUpperCase().equals("POST")) {
			filterChain.doFilter(req, resp);
		} else if (session.getAttribute("user") != null) {
			filterChain.doFilter(req, resp);
		} else {
			request.getRequestDispatcher("/view/login.html").forward(req, resp);
		}
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
	}

}
